﻿var model = avalon.define({
    $id: "APP_QYWD",
    viewkey: "tpllist",
    ListData: [],
    searchkey: "",
    isselall: false,
    isrename: false,
    ishasManage:false,//企业文件夹上传权限
    selall: function () {//全选
        model.isselall = !model.isselall;
        model.ListData.forEach(function (data) {
            data.issel = model.isselall;
            if (model.isselall) {
                model.SelItemData.push(data.$model)
            }
            else {
                ComFunJS.DelItem(model.SelItemData, "ID", data.ID)
            }
        })

    },
    islist: localStorage.getItem("islist") == "true",//是否列表显示
    treefilelist: {
        ID: rootpath, Name: rootpath == "1" ? "企业资料库" : "个人文档", SubFolder: [], SubFileS: []
    },//树的数据
    $computed: {
        nowuser: {//当前用户
            get: function () {
                return ComFunJS.getnowuser();
            }
        },
    },
    getsrc: function (item) {//图片真实路径
        if (item.type == 'folder') {
            return " /images/NewIndex/qywd/file1.png";
        } else {
            if ("jpggifpngbmpjpeg".indexOf(item.FileExtendName.toLowerCase()) >= 0) {
                return ComFunJS.getfileapi() + "/image/" + item.FileMD5;
            }
            else {
                return " /images/NewIndex/qywd/" + item.FileExtendName + ".png";
            }
        }

    },
    GetTreeData: function (treeitem) {
        $.getJSON('/API/FTAPI.ashx?Action=GETLISTDATA', {
            P1: treeitem.ID, P2: ComFunJS.getQueryString("isAdmin"), itemtype: rootpath
        }, function (resultData) {//P1为个人文件夹
            if (resultData.ErrorMsg == "") {
                treeitem.SubFolder.clear()
                treeitem.SubFileS.clear()

                resultData.Result.forEach(function (item) {
                    item.issel = false;
                    item.type = "folder";
                    item.SubFolder = [];
                    item.SubFileS = [];
                    treeitem.SubFolder.push(item);
                })
                resultData.Result1.forEach(function (item) {
                    item.issel = false;
                    item.type = "file";
                    item.SubFolder = [];
                    item.SubFileS = [];

                    treeitem.SubFileS.push(item);
                })
            }
        })
    },
    folderclick: function (item, dom) { //树状的
        $(dom).parent().find("div").eq(0).toggle('normal');
        if (item.ID) {
            model.GetListData(item.ID);
            if (item.SubFileS.size() == 0) {
                model.GetTreeData(item);
            }
        }
        $(".spanli").removeClass("foldersel");
        $(dom).addClass("foldersel");
        model.Pathdata.clear();
        model.Pathdata.push({
            ID: item.ID, Name: item.Name, FolderType: rootpath, Remark: item.Remark, PFolderID: item.PFolderID, FolderLev: "0", active: true
        })
    },
    displist: function () {
        model.islist = !model.islist
        localStorage.setItem("islist", model.islist)
    },
    searchfile: function () {
        if (model.searchkey != "") {
            $.getJSON('/API/FTAPI.ashx?Action=QUERYFILE', {
                P1: rootpath, P2: model.searchkey
            }, function (resultData) {//P1为个人文件夹
                if (resultData.ErrorMsg == "") {
                    resultData.Result.forEach(function (item) {
                        item.issel = false;
                        item.type = "file";
                    })
                    model.ListData = resultData.Result;
                    model.SelItemData.clear();
                    model.viewkey = "querylist";
                }
            })
        }

    },//搜索文档
    clearsearch: function () {
        model.GetListData(rootpath);
        model.searchkey = "";
    },//清楚搜索条件
    jptjsearch: function (event) {
        if (event.ctrlKey && (event.keyCode == 13 || event.keyCode == 10)) {
            model.searchfile();
        }
    },
    GetListData: function (PID) {
        $.getJSON('/API/FTAPI.ashx?Action=GETLISTDATA', {
            P1: PID, P2: ComFunJS.getQueryString("isAdmin"), itemtype: rootpath
        }, function (resultData) {//P1为个人文件夹
            if (resultData.ErrorMsg == "") {
                resultData.Result.forEach(function (item) {
                    item.issel = false;
                    item.type = "folder";
                })
                resultData.Result1.forEach(function (item) {
                    item.issel = false;
                    item.type = "file";

                })
                model.ListData = resultData.Result.concat(resultData.Result1);
                model.SelItemData.clear();
                model.viewkey = "tpllist";
                model.ishasManage = resultData.Result2;

            }
        })
    },//获取目录及文件
    filechange: function (action, b) {
        if (action === "add" || action === "del") {
            $(".wdlist").find(".lifile").contextmenu({
                target: '#context-menu',
                before: function (e, context) {
                    // 隐藏其它右键菜单
                    $("#context-menu1").hide();
                    return true;
                },
                onItem: function (context, e) {
                    if (model.SelItemData.size() > 0) {
                        var itemid = model.SelItemData[0].ID;
                        var itemtype = model.SelItemData[0].type;
                        var action = $.trim($(e.target).text());
                        switch (action) {
                            case "下载":
                                model.downloaditem()
                                break;
                            case "复制":
                                model.copycutdata("copy")
                                break;
                            case "剪切":
                                model.copycutdata("move")
                                break;
                            case "收藏":
                                model.collectitem();
                                break;
                            case "取消收藏":
                                model.cancelcollect();
                                break;
                            case "外部分享":
                                model.ShareItem()
                                break;
                            case "重命名":
                                $(context).find("a").hide();
                                $(context).find("input").show().focus()
                                break;
                            case "内部共享":
                                model.SetAuth()
                                break;
                            case "删除":
                                model.delitems();
                                break;
                            case "属性":
                                model.itemproperty()
                                break;
                            default:
                        }
                    } else {
                        parent.ComFunJS.winwarning("请至少选中一项后再点击");
                    }

                }
            });
        }
    },//数据更新后需要重新加载右键菜单
    viewitem: function (item) {
        if (item.type == "folder") {  //如果是文件夹,进入下一层
            model.GetListData(item.ID)
            var newpath = item.$model;
            model.Pathdata.forEach(function (path) {
                path.active = false;
            })
            newpath.active = true;
            model.Pathdata.push(newpath)
        }
        else {
            if (!item.ISYL) {
                parent.ComFunJS.winwarning("您无法预览此文件");
            }
            else {
                if ("jpggifpngbmpjpeg".indexOf(item.FileExtendName.toLowerCase()) >= 0) { //如果是图片格式，显示图片
                    var imgsrc = ComFunJS.getfileapi() + "/image/" + item.FileMD5;
                    parent.layer.open({
                        type: 1,
                        title: false,
                        maxWidth: 2024,
                        closeBtn: false,
                        skin: 'layui-layer-nobg', //没有背景色
                        shadeClose: true,
                        content: '<div><img src="' + imgsrc + '" ></div>'
                    });

                } else {

                    window.open('/View/Common/WDView.html?ID=' + item.ID);
                }

            }
        }

    },
    Pathdata: [{
        ID: rootpath, Name: rootpath == "1" ? "企业资料库" : "个人文档", FolderType: rootpath, Remark: rootpath, PFolderID: "0", FolderLev: "0", active: true
    }],
    gopath: function (path) {
        model.GetListData(path.ID);
        for (i = model.Pathdata.size() - 1; i >= 0; i--) {
            if (model.Pathdata[i].ID != path.ID) {
                model.Pathdata.pop(model.Pathdata[i])
            } else {
                model.Pathdata[i].active = true;
                return;
            }
        }

    },//目录链接
    selItems: function (item, event) {
        item.issel = !item.issel;
        if (item.issel) {
            model.SelItemData.push(item.$model)
        } else {
            ComFunJS.DelItem(model.SelItemData, "ID", item.ID)
        }
        event.stopPropagation();
    },//多选
    selItem: function (item, event) {
        model.ListData.forEach(function (el) {
            el.issel = item.ID == el.ID;
        })
        model.SelItemData.clear();
        model.SelItemData.push(item.$model)
        event.stopPropagation();

    },//单选
    SelItemData: [],//已选中列表
    filecontextmenu: function (item, event) {
        if (event.button == "2") {
            model.ListData.forEach(function (el) {
                el.issel = item.ID == el.ID;
            })
            model.SelItemData.clear();
            model.SelItemData.push(item.$model)
        }
    },//右键单选
    ShareItem: function () {
        var code = "";
        model.SelItemData.forEach(function (item) {
            code = code + item.ID + "|" + item.type + ",";
        })
        if (code.length > 1) {
            code = code.substring(0, code.length - 1)
        }
        parent.ComFunJS.winviewform("/ViewV3/APPBaseView/QYWD/APP_QYWD_FenX.html?code=" + code, "分享", "700", "550");
        model.ListData.forEach(function (item) {
            if (item.issel) {
                item.ShareCode = "Y";//代指已分享
            }
        })
    },//分享
    SetAuth: function () {
        parent.ComFunJS.winviewform("/ViewV3/APPBaseView/QYWD/APP_QYWD_QX.html?id=" + model.SelItemData[0].ID + "&type=" + model.SelItemData[0].type + "&rootpath=" + rootpath, "权限", "1000");
    },//设置共享权限
    collectitem: function () {
        $.getJSON('/API/FTAPI.ashx?Action=COLLECTITEM', { "P1": model.SelItemData[0].type, "P2": model.SelItemData[0].ID }, function (result) {
            if (result.ErrorMsg == "") {
                parent.ComFunJS.winsuccess("收藏成功");
                model.ListData.forEach(function (item) {
                    if (item.issel) {
                        item.CollectUser = model.nowuser;
                    }
                })
            }
        })
    },//收藏
    cancelcollect: function () {
        $.getJSON('/API/FTAPI.ashx?Action=CANCOLLECTITEM', {
            "P1": model.SelItemData[0].type, "P2": model.SelItemData[0].ID
        }, function (result) {
            if (result.ErrorMsg == "") {
                parent.ComFunJS.winsuccess("取消收藏成功");
                model.ListData.forEach(function (item) {
                    if (item.issel) {
                        item.CollectUser = "";
                    }
                })
            }
        })
    },//取消收藏
    PasteData: [],//粘贴版数据
    copycutdata: function (type) {//复制/剪切
        model.PasteData.clear();
        model.SelItemData.forEach(function (item) {
            model.PasteData.push({
                "ID": item.ID, "PASTETYPE": type, "type": item.type, "Name": item.Name
            });
        })
        parent.ComFunJS.winsuccess("操作成功");

    },
    pasteitem: function () {
        var pid = model.Pathdata[model.Pathdata.length - 1].ID;
        if (ComFunJS.FindItem(model.ListData, function (item) {
                    return item.Name == model.PasteData[0].Name;
        }).length == 0) {
            $.post('/API/FTAPI.ashx?Action=PASTEITEM', {
                "P1": pid, "P2": JSON.stringify(model.PasteData.$model)
            }, function (result) {
                var result = $.parseJSON(result);
                if (result.ErrorMsg == "") {
                    model.GetListData(pid);
                    parent.ComFunJS.winsuccess("粘贴成功");
                }
            })
            model.PasteData.clear();
        }
        else {
            parent.ComFunJS.winwarning("已经存在同名的项,不能粘贴");

        }
    },//粘贴数据
    addfolder: function (dom) {//新建文件夹
        if ($("#conname").val() != "") {
            if (model.checkitemname($("#conname").val())) {
                parent.ComFunJS.winwarning("该目录下已存在相同名称的文件");
            } else {
                var newforder = {
                    Name: $("#conname").val(), FolderType: rootpath
                };
                model.Pathdata.forEach(function (item) {
                    if (item.active) {
                        newforder.PFolderID = item.ID;
                        newforder.FolderLev = item.FolderLev * 1 + 1;
                        newforder.Remark = item.Remark;//路径
                    }
                })//计算新增文件夹的父目录和层级（默认父目录为2,层级为1）
                $(dom).addClass("disabled").find("i").show();
                $.post("/API/FTAPI.ashx?Action=ADDFLODER", {
                    P1: JSON.stringify(newforder)
                }, function (result) {
                    var jsonresult = $.parseJSON(result)
                    $(dom).removeClass("disabled").find("i").hide();
                    if ($.trim(jsonresult.ErrorMsg) != "") {
                        parent.ComFunJS.winwarning(jsonresult.ErrorMsg);
                    } else {
                        parent.ComFunJS.winsuccess("操作成功");
                        jsonresult.Result.issel = false;
                        jsonresult.Result.type = "folder";

                        model.ListData.push(jsonresult.Result)
                        $('#UpdateNameModal').modal('hide');
                        $("#conname").val("")
                    }
                });
            }

        } else {

        }
    },//添加文件夹
    delitems: function () {
        parent.ComFunJS.winconfirm("如果删除目录会删除目录下的所有文件,确认要删除选中项吗", function () {
            $.post('/API/FTAPI.ashx?Action=DELFLODER', {
                P1: JSON.stringify(model.SelItemData.$model)
            }, function (resultData) {//P1为个人文件夹
                var resultData = $.parseJSON(resultData);
                if (resultData.ErrorMsg == "") {
                    parent.ComFunJS.winsuccess("删除成功");
                    ComFunJS.DelItem(model.ListData, "issel", true)
                } else {

                }
            })
        })
    },
    jptj: function (event, dom) {
        if (event.ctrlKey && (event.keyCode == 13 || event.keyCode == 10)) {
            model.addfolder($("#conaddForder"));
        }
    },//键盘添加目录
    addFile: function () {
        parent.ComFunJS.winbtnwin(ComFunJS.getfileapi() + "fileupload", "上传", "800", "500", {
        }, function (layero, index, btdom) {
            btdom.addClass("disabled").find("i").show();
            var frameid = $("iframe", $(layero)).attr('id');
            var nowwin = ComFunJS.isIE() ? parent.window.frames[frameid] : parent.window.frames[frameid].contentWindow;
            var nowfolderid = model.Pathdata[model.Pathdata.length - 1].ID;
            nowwin.location = "/View/Base/Success.html?ID=" + nowfolderid;
            var int = parent.window.setInterval("getwinname()", 1000);//循环等待,直到上传成功并返回文件数据
            parent.window.getwinname = function () {
                try {
                    if (nowwin.filedata) {
                        parent.window.clearInterval(int);
                        var filedata = nowwin.filedata;
                        btdom.removeClass("disabled").find("i").hide();
                        filedata.forEach(function (item) {
                            item.issel = false;
                            item.type = "file";
                        })
                        model.ListData.pushArray(filedata)
                        parent.layer.close(index);
                    };
                } catch (e) {
                }
            }
        });

    },//添加文件
    checkitemname: function (checkname) {
        return ComFunJS.FindItem(model.ListData, function (item) {
            return !item.issel && item.Name == checkname;
        }).length > 0;
    },//验证是否重名
    updatename: function (data, dom) {
        if (dom.val() != data.Name) {
            if ($.trim(dom.val()) == "") {
                parent.ComFunJS.winwarning("不能为空");
                dom.val(data.Name);
                return;
            }
            if (model.checkitemname(dom.val())) {
                parent.ComFunJS.winwarning("该目录下已存在相同名称的文件");
                dom.val(data.Name);
                return;
            } else {
                $.post('/API/FTAPI.ashx?Action=UPDATENAME', {
                    "P1": data.type, "P2": data.ID, "Name": dom.val()
                }, function (result) {
                    var result = $.parseJSON(result);
                    if (result.ErrorMsg == "") {
                        parent.ComFunJS.winsuccess("修改成功");
                        dom.hide().parent().find("a").text(dom.val())
                    }
                })
            }
        }
        dom.hide().parent().find("a").show();


    },//修改名称
    itemproperty: function () {
        var path = "/";
        model.Pathdata.forEach(function (item) {
            path = path + item.Name + "/";
        })
        parent.ComFunJS.winviewform("/ViewV3/APPBaseView/QYWD/APP_QYWD_SX.html?path=" + escape(path) + "&id=" + model.SelItemData[0].ID + "&type=" + model.SelItemData[0].type, "属性", "700", "550");
    },//属性
    downloaditem: function () {
        if (model.SelItemData.size() == 1 && model.SelItemData[0].type == "file") {
            ComFunJS.winold("/View/Common/DownLoadFile.aspx?MD5=" + model.SelItemData[0].FileMD5)
        } else {
            var code = "";
            model.SelItemData.forEach(function (item) {
                code = code + item.ID + "|" + item.type + ",";
            })
            if (code.length > 1) {
                code = code.substring(0, code.length - 1)
            }
            parent.ComFunJS.winviewform("/View/Common/DownFolder.html?code=" + code, "下载文件", "550", "450")
        }
    },
    menuattr: {
        issc: false, isfx: false, isgx: false
    }
})

model.$watch("SelItemData.length", function (newval, oldval) {
    if (newval * 1 > 0) {
        model.menuattr.isfx = model.SelItemData[0].ShareCode;
        model.menuattr.isgx = model.SelItemData[0].ViewAuthUsers || model.SelItemData[0].DownloadAuthUsers || model.SelItemData[0].UploadaAuthUsers;
        model.menuattr.issc = model.SelItemData[0].CollectUser.indexOf(model.nowuser) >= 0
    }
})

